package com.zhkj.txg.module.mine.ui

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.mine.adapter.PublishAdapter
import com.zhkj.txg.module.mine.vm.ArticleViewModel
import kotlinx.android.synthetic.main.activity_publish.*

class PublishListActivity : ViewModelActivity<ArticleViewModel>() {
    override fun setViewModel(): ArticleViewModel = createViewModel()
    override fun statusTitleBar(): View? = titlePublish
    override val layoutResId: Int = R.layout.activity_publish

    private val publishAdapter = PublishAdapter().apply {
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.getPublishArticle(false)
        }
    }

    override fun initUI() {
        with(rvPublish) {
            layoutManager = LinearLayoutManager(this@PublishListActivity)
            adapter = publishAdapter
        }
        publishAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshPublish.setOnRefreshListener { initData() }
    }

    override fun initData() {
        viewModel.getPublishArticle(true)
    }

    override fun initViewModel() {
        viewModel.articleListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshPublish.finishRefresh()
                    else if (it.hasMore) publishAdapter.loadMoreModule?.loadMoreComplete()
                    else publishAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) publishAdapter.addData(it.data)
                    else publishAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1)publishAdapter.loadMoreModule?.loadMoreFail()
                    else refreshPublish.finishRefresh(false)
                }
            }
        })
    }
}